<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Account/classes/PhpFox_ComponentBrowse.class.php, $Author:  $ */



/** Component for browsing members in public area
 *
 * @version $Id: PhpFox_ComponentBrowse.class.php 420 2008-03-31 14:40:31Z phpfoxsv $
 * @package module.account
 */
class PhpFox_Mod_Account_ComponentBrowse extends BaseComponent
{
    function process()
    {
        //initialization
        $oAccountItem = &$this->_oModule->getItem('Account');
        /* @var $oAccountItem PhpFox_Mod_Account_ItemAccount */
        $oReq = &App::getRequest();
        /* @var $oReq Request */
        $oUrl = &App::getUrl();
        /* @var $oUrl Url */
        $oAccountSrv = &$this->_oModule->getService('Account');
        /* @var $oAccountSrv PhpFox_Mod_Account_ServiceAccount */
        $oSecurityService = &$this->_oModule->getService('Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oCustomFieldService = &$this->_oModule->getService('CustomField');
	    /* @var $oCustomFieldService PhpFox_Mod_Account_ServiceCustomField */
        $oTpl = &$this->_oModule->getTemplate();
        App::loadClass('Filter');
        App::loadClass('Pager');
        
        $oSecurityService->checkAccess('browse');
        $oSecurityService->checkPerm('account', array('full', 'read_only'));
        $bIsAdmin = $oSecurityService->isAdmin();
        $bIsStaff = $oSecurityService->isStaff(null, true);
        if ($iUserId = $oReq->getInt('makefeature'))
        {
            $oAccountItem->load($iUserId);
            if ( App::isStaff() )
            {
                $oAccountItem->aData['feature'] = ($oAccountItem->aData['feature']) ? '' : 1;
                $oAccountItem->update(array('feature'));
            }
            $oUrl->clearParams('makefeature');
            App::rmCache('featured_members.php');
            App::forward($oUrl->getUrl());
        }
        $aFields = $oCustomFieldService->getFieldsList();
        $sMode = $oReq->get('mode', 'recent');
        $bLoggedIn = false;
        if ($oSecurityService->getCurrentUserLogin())
        {
            $bLoggedIn = true;
        }

		$aState = array();
        foreach (App::getOptions('us_stat') as $sVal)
        {
            $aState[$sVal] = $sVal;
        }

        $aAge = array();
        $aAge[''] = App::format('core.any');
        for ($i = 16; $i <= 100; $i++)
        {
            $aAge[$i] = '&nbsp;'.$i;
        }
        $bUs = App::getSetting('us_states');
        $aFieldsList = array
        (
            'user'       => App::format('core.username'),
            'city'       => App::format('core.city'),
            'email'      => App::format('core.Email')
        );

        $oSrvCustom = &App::getModuleService('Account', 'CustomField');
        $aCustomTextFields = $oSrvCustom->getBrowseTextNames();
        if ( count($aCustomTextFields) > 0 )
        {
			foreach($aCustomTextFields as $sCustomText)
			{
        		$aFieldsList[$sCustomText['id']] = ucfirst(strtolower($sCustomText['name']));
        	}
		}

		$aLocation = App::getOptions('country');
		$aGenders = App::getOptions('gender');

        $aFilter = array
        (
            'gender' => array
            (
                'value'  => '=',
                'select' => $aGenders,
                'def'    => '',
            ),
            'location' => array
            (
                'value'  => '=',
                'select' => $aLocation,
            ),
            'city' => 'like',
            'age' => array
            (
                'value'  => 'range',
                'select' => $aAge,
            ),
            'state' => array
            (
                'value'  => '=',
                'select' => $aState,
            ),
            'zip' => 'like',
            'user' => 'like',
            'fields_list' => array
            (
                'value'  => '=',
                'select' => $aFieldsList,
                'def'    => 'user',
            ),
            'field_value' => 'like',
        );

        $aCustomFieldsNames = array();
        foreach ($aFields as $aField)
        {
            $aOptions = array();
            $aOptions[''] = App::format('core.any');
            $aOptions = $aOptions + $aField['options'];
            $aFilter['field'.$aField['custom_field_id']] = array
            (
                'value'  => '=',
                'select' => $aOptions,
            );
            $aCustomFieldsNames[] = 'field'.$aField['custom_field_id'];
        }
        $iPageSize = App::getParam('public.pagesize');
        $iPage = $oReq->getInt('page', 1);
        $aCustomData = array();
        if ($sCountry = $oReq->get('country'))
        {
            $aFilter['location']['def'] = $sCountry;
            $aCustomData['location'] = $sCountry;
        }
        $oFilter = &new Filter('browse', $aFilter, $aCustomData);
        $bPager = true;
        switch ($sMode)
        {
            case 'new':
                $aCond['signup'] = '>= '.(time() - App::getParam('public.browse.new_members_days'));
                $sOrder = 'signup DESC';
                // $iPageSize = 9;
                // $iPage = 1;
                // $bPager = false;
                break;
            case 'updated':
                $aCond = array();
                $iTime = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $aCond['p_update'] = '> '.$iTime;
                $sOrder = 'p_update DESC';
                break;
            case 'featured':
                $aCond = array();
                $aCond['feature'] = ' = 1';
                $sOrder = 'feature';
                break;
            default:
                $aCond = array();
                $sOrder = 'login DESC';
        }
        $aTextCond = array();
        $aJoinCond = array();
        foreach ($oFilter->aConditions as $sKey => $sValue)
        {
            if (in_array($sKey, $aCustomFieldsNames))
            {
                $iFieldId = intval(substr($sKey, 5));
                $sValue = preg_replace('#{\#(.*)}#i', 'cf2u.custom_option_id', $sValue);
                $aJoinCond[] = '(cf2u.custom_field_id = "'.$iFieldId.'" AND '.$sValue.')';
            }
            elseif ($sKey == 'field_value')
            {
            	$iFieldId = $oFilter->aData['fields_list'];
            	if ( is_numeric($iFieldId) )
            	{
                	$sValue = preg_replace('#{\#(.*)}#i', 'cfText.textarea', $sValue);
                	$aTextCond[] = '(cfText.custom_field_id = "'.$iFieldId.'" AND '.$sValue.')';
                }
                else
                {
                	$sValue = preg_replace('#{\#(.*)}#i', $iFieldId, $sValue);
                	$aCond[] = $sValue;
                }
            }
            elseif ($sKey == 'age')
            {
                $sCondition = '';
                $iDay = date('d');
                $iMonth = date('m');
                $iYear = date('Y');
                $sToDate = '';
                $sFromDate = '';
                if ($oFilter->aData['age_from'])
                {
                    $iDate = mktime(0, 0, 0, $iMonth, $iDay, $iYear - $oFilter->aData['age_from']);
                    $sFromDate = date('Y-m-d', $iDate);
                }
                if ($oFilter->aData['age_to'])
                {
                    $iDate = mktime(0, 0, 0, $iMonth, $iDay, $iYear - $oFilter->aData['age_to']);
                    $sToDate = date('Y-m-d', $iDate);
                }
                if ($sFromDate)
                {
                    $sCondition = 'STR_TO_DATE(CONCAT_WS("-", u.year, u.month, u.day), "%Y-%m-%d") < "'.$sFromDate.'"';
                }
                if ($sToDate)
                {
                    if ($sCondition)
                    {
                        $sCondition .= ' AND ';
                    }
                    $sCondition .= 'STR_TO_DATE(CONCAT_WS("-", u.year, u.month, u.day), "%Y-%m-%d") > "'.$sToDate.'"';
                }
                if ($sCondition)
                {
                    $aCond[] = $sCondition;
                }
            }
            elseif (($sKey != 'field_value') && ($sKey != 'fields_list'))
            {
                if (!$bUs && (($sKey == 'zip') || ($sKey == 'state')))
                {
                    continue;
                }
                $aCond[] = $sValue;
            }
        }
        $aCond['verify'] = '<> 1';
        $aCond['is_banned'] = '!= 1';

        list($aItems, $iCnt) = $oAccountSrv->browseUsers($aTextCond, $aJoinCond, $aCond, $iPage, $iPageSize, $sOrder, ('online' == $sMode ? true : false));
        foreach ($aItems as $iKey => $aItem)
        {
            $aItems[$iKey]['age'] = $oAccountSrv->getAge($aItem);
        }

        $oUrl->setParam('display', $oReq->get('display'));
        $oTpl->assignSrc('aFilter', $oFilter->aHtml);
        if ($bPager)
        {
            $oPager = &new Pager($iCnt, $iPage, $iPageSize);
            $oTpl->assign(array(
                'aPaging' => ($iCnt) ? $oPager->getInfo($oUrl) : '',
            ));
        }
        
        if ($oReq->getAction() == 'browse_show' && !count($aItems))
        {
        	$oFilter->reset();
        }        

        $oTpl->assign(array(
            'aItems'    => $aItems,
            'sMode'     => $sMode,
            'aFields'   => $aFields,
            'bUs'       => $bUs,
            'bAdmin'    => $bIsAdmin,
            'bIsStaff'  => $bIsStaff,
            'bLogged'   => $bLoggedIn,
            'bNames'    => ($oReq->get('val[display]') == '') ? true : false,
            'bFiltered' => ($oReq->getAction() == 'browse_show') ? true : false,
            'iCnt'      => $iCnt,
            'bDisplay'  => ($oReq->get('display') == 1) ? true : false,
            'sImageUrl' => App::getParam('user.pic.url'),
            'bShowPoints'      => !App::getSetting('profile_display_points'),
        ));
        return $oTpl->fetch('BrowseList.html');
    }
}
?>